//
//  Bottom1ViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/17.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import SwiftyJSON
import UIAlertController_Blocks

class Bottom1ViewController: BaseViewController, LTTableViewProtocal, UITableViewDataSource, UITableViewDelegate{
    
    
    var type:Int = 0//0、交易中，1、当前竞价；2、本战场成交；3、标的清单；
    
    var jiaoyiType:Int = 0//0、竞价；1、挂牌；2、协商
    
    var sessinid:String?
    
    var targets:[JSON] = [JSON]()
    
    var datas:[JSON] = [JSON]()
    
    var fair_id:String!
    
    var timer : DispatchSourceTimer?
    
    
    var statusS:Int = 0
    var cutdowncount:Int = 0
    
    
    var tableView:UITableView = UITableView()
    
//    public lazy var tableView: UITableView = {
//
////        return tableView
//    }()
    
    func startTimer() -> Void {
        
        var data = [JSON]()
        self.targets.forEach({ (d) in
            var ds = [String:Any]()
            if d["countdown_ttl"].intValue <= 0 {
                data.append(jsonFormater(data: d))
            }else {
                ds = d.dictionaryObject!
                ds["countdown_ttl"] = d["countdown_ttl"].intValue - 1
                data.append(jsonFormater(data: ds))
            }
        })
        self.targets = data
        UIView.performWithoutAnimation {
            
            self.tableView.reloadData()
        }
    }
    
    func showType(t:Int) -> Bottom1ViewController {
        self.type = t
        return self
    }
    
    func jiaoyiT(t:Int) -> Bottom1ViewController {
        self.jiaoyiType = t
        return self
    }
    
    func fair_id(f:String) -> Bottom1ViewController {
        self.fair_id = f
        return self
    }
    
    func sessionId(t:String) -> Void {
        self.sessinid = t
        if self.sessinid?.isEmpty == true {
            return
        }
        if self.type == 0 {
            NetWorkRequest(.jingjiaing(id: self.fair_id, sid: t)) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    self.datas.removeAll()
                    jsonFormater(data: res["data"] as Any).arrayValue.forEach({ (js) in
                        self.datas.append(js)
                    })
                    (UIApplication.shared.delegate as! AppDelegate).tartget = self.datas
                    
                    self.tableView.reloadData()
                }
            }
        }else {
            NetWorkRequest(.jingjiabid(id: self.fair_id,sid: t)) { (res) -> (Void) in
                let jd = jsonFormater(data: res)
                if jd["code"].stringValue == "000000" && jd["data"].dictionaryValue["data"]?.arrayValue.isEmpty == false {
                    self.datas.removeAll()
                    jd["data"].dictionaryValue["data"]?.arrayValue.forEach({ (j) in
                        
                        (UIApplication.shared.delegate as! AppDelegate).tartget.forEach({ (t) in
                            if j["tid"].intValue == t["id"].intValue {
                                self.datas.append(t)
                            }
                        })
                    })
                    
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    public func DispatchTimer(timeInterval: Double, handler:@escaping (DispatchSourceTimer?)->())
    {
        timer?.cancel()
        timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        timer?.schedule(deadline: .now(), repeating: timeInterval)
        timer?.setEventHandler {
            DispatchQueue.main.async {
                handler(self.timer)
            }
        }
        timer?.resume()
    }
    
    public func clearData()-> Void {
        self.datas.removeAll()
        
        self.tableView.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        
        
        let H: CGFloat = glt_iphoneX ? (view.bounds.height - 64 - 24 - 34) : view.bounds.height  - 64
        tableView = tableViewConfig(CGRect(x: 0, y: 0, width: view.bounds.width, height: H), self, self, nil)
        
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.rowHeight = 293
        if #available(iOS 11.0, *) {
            tableView.estimatedRowHeight = 0
            tableView.estimatedSectionHeaderHeight = 0
            tableView.estimatedSectionFooterHeight = 0
        }
        
        
        
        view.addSubview(tableView)
        
        
        
        
        
        tableView.tableFooterView = UIView();
        tableView.register(R.nib.buyingTableViewCell(), forCellReuseIdentifier: "buyingTableViewCell")
        tableView.register(R.nib.emptyTableViewCell(), forCellReuseIdentifier: "emptyTableViewCell")
        
        glt_scrollView = tableView
        
        if self.jiaoyiType == 0 || self.jiaoyiType == 1 {
            
        }else {
            loadData()
        }
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        tableView.contentOffset = CGPoint(x: 0, y: -221-44)
        tableView.separatorStyle = .none
        
        if self.jiaoyiType == 1 || self.jiaoyiType == 2 {
            tableView.rowHeight = 260
        }else {
            tableView.rowHeight = 293
        }
    }
    
    
    func loadData() {
        
        if self.statusS != 3 && self.type != 2 {
            self.datas.removeAll()
            
            self.tableView.reloadData()
            return
        }
        
        if self.jiaoyiType == 0 {//竞价
            
            if self.type == 0 {//交易中
                
            }else if self.type == 1 {
                
            }else if self.type == 2 {
                NetWorkRequest(.jingjiawin(id: self.fair_id)) { (res) -> (Void) in
                    let jd = jsonFormater(data: res)
                    if jd["code"].stringValue == "000000" && jd["data"].dictionaryValue["data"]?.arrayValue.isEmpty == false {
                        self.datas.removeAll()
                        self.datas = jd["data"].dictionaryValue["data"]?.arrayValue ?? [JSON]()
//                        jd["data"].dictionaryValue["data"]?.arrayValue.forEach({ (j) in
//                            self.datas.append(j)
//                        })

                        self.tableView.reloadData()
                    }
                }
            }else if self.type == 3 {
                NetWorkRequest(.jingjiatab(id: self.fair_id)) { (res) -> (Void) in
                    let jd = jsonFormater(data: res)
                    if jd["code"].stringValue == "000000" && jd["data"].dictionaryValue["data"]?.arrayValue.isEmpty == false {
                        self.datas.removeAll()
                        self.datas = jd["data"].dictionaryValue["data"]?.arrayValue ?? [JSON]()
//                        self.tableView.layoutIfNeeded()
//                        self.tableView.beginUpdates()
                        
                        self.tableView.reloadData()
//                        self.tableView.endUpdates()
                    }
                }
            }
            
        }else if self.jiaoyiType == 1 {//挂牌
            if self.type == 0 {
                NetWorkRequest(.guapairuntime(id: self.fair_id)) { (res) -> (Void) in
                    let jd = jsonFormater(data: res)
                    self.datas.removeAll()
                    if jd["code"].stringValue == "000000" && jd["data"].dictionaryValue["items"]?.arrayValue.isEmpty == false {
                        
                        jd["data"].dictionaryValue["items"]?.arrayValue.forEach({ (j) in
                            self.datas.append(j)
                        })
                        
                    }
                    
                    self.tableView.reloadData()
                }
            }else if self.type == 2 {
                NetWorkRequest(.guapaiwin(id: self.fair_id)) { (res) -> (Void) in
                    let jd = jsonFormater(data: res)
                    if jd["code"].stringValue == "000000" && jd["data"].dictionaryValue["data"]?.arrayValue.isEmpty == false {
                        self.datas.removeAll()
                        jd["data"].dictionaryValue["data"]?.arrayValue.forEach({ (j) in
                            self.datas.append(j)
                        })
                        
                        self.tableView.reloadData()
                    }
                }
            }
            
            
        }else {//协商
            
            if self.type == 0 {
                NetWorkRequest(.xieshangruntime(id: self.fair_id)) { (res) -> (Void) in
                    let jd = jsonFormater(data: res)
                    self.datas.removeAll()
                    if jd["code"].stringValue == "000000" && jd["data"].dictionaryValue["items"]?.arrayValue.isEmpty == false {
                        
                        jd["data"].dictionaryValue["items"]?.arrayValue.forEach({ (j) in
                            self.datas.append(j)
                        })                        
                    }
                    
                    self.tableView.reloadData()
                }
            }else if self.type == 2 {
                NetWorkRequest(.xieshangwin(id: self.fair_id)) { (res) -> (Void) in
                    let jd = jsonFormater(data: res)
                    if jd["code"].stringValue == "000000" && jd["data"].dictionaryValue["data"]?.arrayValue.isEmpty == false {
                        self.datas.removeAll()
                        jd["data"].dictionaryValue["data"]?.arrayValue.forEach({ (j) in
                            self.datas.append(j)
                        })
                        
                        self.tableView.reloadData()
                    }
                }
            }
            
        }
        
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.datas.count <= 0 {
            return 1
        }
        return self.datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.datas.count <= 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "emptyTableViewCell") as! EmptyTableViewCell
            cell.selectionStyle = .none

            if self.type == 0 && self.statusS != 3{
                cell.labelContent.text = "专场已开启，请等待交易"
            }else {
                cell.labelContent.text = "暂无符合条件的信息"
            }
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "buyingTableViewCell") as! BuyingTableViewCell
        cell.selectionStyle = .none
        
        let formater = NumberFormatter()
        
        formater.positiveFormat = "#0.####"
        
        let jd = self.datas[indexPath.row]
        
        cell.labelNo.text = "标的号：\(jd["alias"].stringValue)"
        cell.labelStatus.text = jd["status_text"].stringValue
        cell.labelCate.text = jd["variety_name"].stringValue
       
        cell.labelNum.text = "\(jd["num"].stringValue)"
        
//        cell.labelNum.text = jd[""]
        cell.labelLevel.text = jd["grade_text"].stringValue
        
        cell.labelDanwei.text = jd["depot_name"].stringValue
        
        cell.btnBase.isHidden = false
        cell.btnBase.setImage(nil, for: .normal)
        cell.labelTime.textColor = .black
        let formaterm = NumberFormatter()
        
        formaterm.positiveFormat = "#0.00"
        
        if self.jiaoyiType == 0 {
            cell.labelNum.text = jd["base_price"].stringValue
            self.targets.forEach({ (r) in
                if r["tid"].stringValue == jd["id"].stringValue {
                    cell.btnBase.setTitle("\(jd["base_price_yuan"].floatValue + r["new_price"].floatValue)", for: .normal)
                    cell.btnBase.setTitle("\(jd["base_price_yuan"].floatValue + jd["new_price"].floatValue)", for: .disabled)
                    if r["new_price"].stringValue.isEmpty {
                        cell.labelNew.text = ""
                    }else {
                        cell.labelNew.text = "\(formaterm.string(from: NSNumber.init(value: r["new_price"].floatValue))!) \(jd["price_unit_text"].stringValue)"
                    }
                    
                    if (UIApplication.shared.delegate as! AppDelegate).show_target_ttl_at >= r["countdown_ttl"].intValue {
                        cell.labelTime.text = r["countdown_ttl"].stringValue
                    }else {
                        cell.labelTime.text = ""
                    }
                }
            })
            
            
            if jd["can_biding"].boolValue == false {
                
                cell.btnBase.isEnabled = false
                cell.btnBase.setTitle("委托方不能应价", for: .normal)
                cell.btnBase.setTitle("委托方不能应价", for: .disabled)
            }else {
                
                cell.btnBase.isEnabled = true
                //                    cell.btnBase.setImage(UIImage.init(named: "新"), for: .normal)
                cell.btnBase.setTitle("\(jd["base_price_yuan"].floatValue + jd["alarm_price"].floatValue)", for: .normal)
                cell.btnBase.setTitle("\(jd["base_price_yuan"].floatValue + jd["alarm_price"].floatValue)", for: .disabled)
                
                self.targets.forEach({ (r) in
                    if r["tid"].stringValue == jd["id"].stringValue {
                        
                        if r["new_price_show"].stringValue.isEmpty {
                            
                        }else {
                            
                            
                            
                            
                        if (UIApplication.shared.delegate as! AppDelegate).isBuy == 0 {//买房
                            cell.btnBase.setTitle("\(r["new_price_show"].floatValue + r["offer_step"].floatValue )", for: .normal)
                            
                            cell.btnBase.setTitle("\(r["new_price_show"].floatValue + r["offer_step"].floatValue )", for: .disabled)
                            
                            if jd["max_price_flag"].intValue == 1 {
                            
                                if (r["new_price_show"].floatValue + r["offer_step"].floatValue ) > jd["max_price_yuan"].floatValue {
                                    cell.btnBase.isEnabled = false
                                    cell.btnBase.setTitle("已达到最高限价", for: .normal)
                                    cell.btnBase.setTitle("已达到最高限价", for: .disabled)
                                    
                                }
                            }
                        }else {//卖方
                            cell.btnBase.setTitle("\(r["new_price_show"].floatValue - r["offer_step"].floatValue )", for: .normal)
                            
                            cell.btnBase.setTitle("\(r["new_price_show"].floatValue - r["offer_step"].floatValue )", for: .disabled)
                            
                            if (r["new_price_show"].floatValue - r["offer_step"].floatValue ) <= 0 {
                                cell.btnBase.isEnabled = false
                                cell.btnBase.setTitle("已为最低报价", for: .normal)
                                cell.btnBase.setTitle("已为最低报价", for: .disabled)
                                
                            }
                        }
                            
                            
                        if r["ent_id"].intValue == (UIApplication.shared.delegate as! AppDelegate).enterprise_id {
                            cell.btnBase.isEnabled = false
                            cell.btnBase.setImage(UIImage.init(named: "新"), for: .disabled)
                            cell.btnBase.setImage(UIImage.init(named: "新"), for: .normal)
                        }
                            
                            
                        }
                        
                        
                    }
                })
                
            }
            
            cell.labelLowPrice.text = "\(formaterm.string(from: NSNumber.init(value:jd["base_price_yuan"].floatValue))!) \(jd["price_unit_text"].stringValue)"
            if self.type == 0 {
                
            }else if self.type == 3 {
                cell.btnBase.isEnabled = true
                cell.btnBase.setImage(UIImage(), for: .normal)
                cell.btnBase.setTitle("查看详情", for: .normal)
                
                cell.labelLjishi.text = "交易节："
                cell.labelTime.text = jd["number"].stringValue
                cell.labelLNew.text = ""
                cell.labelLowPrice.text = "\(formaterm.string(from: NSNumber.init(value:jd["base_price_show"].floatValue))!) \(jd["price_unit_text"].stringValue)"
                
            }else if self.type == 2 {
                cell.labelLjishi.text = "成交价格:"
                cell.labelTime.text = "\(formaterm.string(from: NSNumber.init(value:jd["win_price_show"].floatValue))!) \(jd["price_unit_text"].stringValue)"
                cell.labelLNew.text = "成交时间:"
                cell.labelNew.text = "\(jd["won_at"].stringValue)"
                cell.btnBase.isHidden = true
                cell.labelNum.text = formater.string(for:jd["num"].numberValue)
            }else {
                cell.btnBase.isHidden = true
            }
        }else {
            cell.labelTime.textColor = .red
            if self.jiaoyiType == 2 {//协商
                
                cell.labelLjishi.text = "标价："
                cell.labelTime.text = "\(formaterm.string(from: NSNumber.init(value:jd["base_price"].floatValue))!) \(jd["price_unit_text"].stringValue)"
                cell.labelLLow.text = "粮原地："
                cell.labelLowPrice.text = jd["grain"].stringValue
//                    if
                cell.labelNum.text = formater.string(for:jd["num"].numberValue)
                cell.labelLNew.text = "报价(元/吨):"
                if jd["offer_price"].floatValue > 0 {
                    cell.labelNew.text = formaterm.string(from: NSNumber.init(value:jd["offer_price"].floatValue))
                }else {
                    cell.labelNew.text = ""
                }
                if self.type != 0 {
                    cell.btnBase.isHidden = true
                    cell.btnBase.isHidden = true
                    cell.labelLNew.text = ""
                    cell.labelNew.text = ""
                    cell.labelLLow.text = "成交时间："
                    cell.labelNum.text = "\(jd["deal_num"].stringValue)"
                    cell.labelLowPrice.text = jd["deal_at"].stringValue
                    
                }
                
            }else {//挂牌
                if self.type != 0 {
                    cell.btnBase.isHidden = true
                    cell.labelLLow.text = "成交时间："
                    cell.labelNum.text = formater.string(for:jd["deal_num"].numberValue)
                    cell.labelLowPrice.text = jd["deal_at"].stringValue
                }else {
                    cell.labelLLow.text = "粮原地："
                    cell.labelLowPrice.text = jd["grain"].stringValue
                    if jd["reset_num"].floatValue == jd["num"].floatValue {
                        cell.labelNum.text = formater.string(for:jd["num"].numberValue)
                    }else {
                        cell.labelNum.text = "\(jd["reset_num"].stringValue) / \(jd["num"].stringValue)"
                    }
                }
                
                cell.labelLjishi.text = "标价："
                cell.labelTime.text = "\(formaterm.string(from: NSNumber.init(value:jd["base_price"].floatValue))!) \(jd["price_unit_text"].stringValue)"
                cell.labelLNew.text = ""
                cell.labelNew.text = ""
            }
            
//                cell.labelLowPrice.text = "\(jd["price_yuan"].stringValue) \(jd["price_unit_text"].stringValue)"
            if jd["is_win"].intValue == 2 {
                cell.btnBase.isEnabled = false
                cell.btnBase.setTitle("委托方不能应价", for: .normal)
            }else {
                cell.btnBase.isEnabled = true
                cell.btnBase.setTitle("报价", for: .normal)
                
                
                
                if self.jiaoyiType == 1 {
                    cell.btnBase.setTitle("\(jd["price_yuan"].stringValue)", for: .normal)
                    cell.btnBase.setTitle("\(jd["price_yuan"].stringValue)", for: .disabled)
                }else {
                    if jd["offer_status"].dictionaryValue["fair_id"]?.stringValue.isEmpty == false {
                        cell.btnBase.setTitle("已报价", for: .normal)
                    }
                }
            }
            if jd["is_client"].boolValue {
                cell.btnBase.isEnabled = false
                cell.btnBase.setTitle("委托方不能应价", for: .normal)
                cell.btnBase.setTitle("委托方不能应价", for: .disabled)
            }
        }
        
        cell.show = {[weak self] () -> Void in
            
            
            
            
            
            if self?.type == 0 {//应价中
                if (UIApplication.shared.delegate as! AppDelegate).isplayData.count > 0 {
                    UIAlertController.showAlert(in: self!, withTitle: "提示", message: "游客模式不可应价", cancelButtonTitle: "确定", destructiveButtonTitle: nil, otherButtonTitles: nil, tap: { (vc, ac, index) in
                        
                    })
                    return
                }
                if self?.jiaoyiType == 0 { //竞价
                    
                    self?.targets.forEach({ (r) in
                        if r["tid"].stringValue == jd["id"].stringValue {
                            let jingjia = DialogXieshang.showView(frame: (self?.parent?.view.bounds)!, data: jd, tagget: r)
                            jingjia.ob = {[weak self] (d) -> Void in
                                let js = jsonFormater(data: d)
                                NetWorkRequest(.jingjiast(fid: self?.fair_id ?? "", sid: self?.sessinid ?? "", tid: jd["id"].stringValue, bid_price: js["price"].stringValue, last_price: js["last_price"].stringValue), completion: { (res) -> (Void) in
                                    jingjia.removeFromSuperview()
                                    showMessage(message: res["message"] as! String)
                                    if res["code"] as! String == "000000" {
                                        self?.loadData()
                                    }
                                })
                            }
                            self?.parent?.view.addSubview(jingjia)
                        }
                    })
                    
                    
                }else if self?.jiaoyiType == 1 {//挂牌
                    let guapai = DialogGuapai.showView(frame: (self?.parent?.view.bounds)!, data: jd, fid:(self?.fair_id)!)
                    guapai.ob = {[weak self] (d) -> Void in
                        
                        let js = jsonFormater(data: d)
                        
                        NetWorkRequest(.guapaibiding(fid: self?.fair_id ?? "", tid: jd["id"].stringValue, num: js["price"].stringValue), completion: { (res) -> (Void) in
                            showMessage(message: res["message"] as! String)
                            guapai.removeFromSuperview()
                            if res["code"] as! String == "000000" {
                                self?.loadData()
                            }
                        })
                    }
                    self?.parent?.view.addSubview(guapai)
                }else if self?.jiaoyiType == 2 {//协商
                    let xieshang = DialogJingjia.showView(frame: (self?.parent?.view.bounds)!, data: jd)
                    xieshang.ob = {[weak self] (d) -> Void in
                        let js = jsonFormater(data: d)
                        NetWorkRequest(.xieshangbiding(fid: (self?.fair_id)!, tid: jd["id"].stringValue, price: js["price"].stringValue, content: js["note"].stringValue, delivery_point: js["address"].stringValue), completion: { (res) -> (Void) in
                            showMessage(message: res["message"] as! String)
                            xieshang.removeFromSuperview()
                            if res["code"] as! String == "000000" {
                                self?.loadData()
                            }
                        })
                        
                        
                    }
                    self?.parent?.view.addSubview(xieshang)
                }
                
            }else {
                let vc = R.storyboard.home.biaoDescViewController()!
                vc.fair_id = self?.fair_id
                vc.target_id = jd["id"].stringValue
                self?.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        
        
        
        
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
}
